﻿using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System;
using System.ComponentModel;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using System.Collections.Generic;
using WebPart = System.Web.UI.WebControls.WebParts.WebPart;

namespace CodeArt.SharePoint.SmartQuery
{
    internal class FieldCheckBoxGroup : Table
    {
        private int _maxLength = 0;
        private int _index = -1;

        const string CheckboxIDPrefix = "_ShouldDisplay_";

        public int MaxLength
        {
            get { return _maxLength; }
            set { _maxLength = value; }
        }

        public FieldCheckBoxGroup(int maxLength)
        {
            this._maxLength = maxLength;
            this.Width = Unit.Percentage(100);
            this.Attributes.Add("cellPadding", "2");
            this.Attributes.Add("cellSpacing", "0");
            this.Attributes.Add("border", "0");

            this.CreateHeader();
        }

        private void CreateHeader()
        {
            TableRow sel_hr = new TableRow();
            TableCell sel_Cell1 = CreateFieldCell();
            sel_Cell1.HorizontalAlign = HorizontalAlign.Center;
            sel_Cell1.VerticalAlign = VerticalAlign.Top;
            sel_Cell1.Attributes.Add("nowrap", "true");
            sel_Cell1.Controls.Add(new HeaderTextControl(ResourcesHelper.GetResourceString("lbDisplay","显示")));

            sel_hr.Controls.Add(sel_Cell1);

            sel_hr.Controls.Add(CreateSeperatorCell());

            TableCell sel_cell2 = CreateFieldCell();
            sel_cell2.VerticalAlign = VerticalAlign.Top;
            sel_cell2.Controls.Add(new HeaderTextControl(ResourcesHelper.GetResourceString("lbField","栏名")));
            sel_hr.Controls.Add(sel_cell2);

            TableCell sel_Cell3 = CreateFieldCell();
            sel_Cell3.HorizontalAlign = HorizontalAlign.Center;
            sel_Cell3.VerticalAlign = VerticalAlign.Top;
            sel_Cell3.Attributes.Add("nowrap", "true");
            sel_Cell3.Controls.Add(new HeaderTextControl(ResourcesHelper.GetResourceString("lbPosition", "位置")));
            sel_hr.Controls.Add(sel_Cell3);

            sel_hr.Controls.Add(CreateSeperatorCell());

            this.Controls.Add(sel_hr);
        }

        internal static TableCell CreateFieldCell()
        {
            TableCell sel_cell2 = new TableCell();
            //sel_cell2.Attributes.Add("class", "ms-authoringcontrols");
            return sel_cell2;
        }

        internal static TableCell CreateSeperatorCell()
        {
            TableCell sel_cell2 = new TableCell();
            //sel_cell2.Attributes.Add("class", "ms-authoringcontrols");
            sel_cell2.Attributes.Add("width", "10");
            sel_cell2.Controls.Add(new LiteralControl("&nbsp;"));
            return sel_cell2;
        }

        public void AddSeparatorItem()
        {
            TableRow row1 = new TableRow();
            TableCell cell1 = new TableCell();
            cell1.Attributes.Add("colspan", "5");
            cell1.Controls.Add(new ToolPartItemSeparator());
            row1.Controls.Add(cell1);
            this.Rows.Add(row1);
        }

        public void AddCheckField(SPField field, bool isChecked)
        {
            this._index++;

            TableRow row1 = new TableRow();
            //FieldCheckBox fCheck = CreateFieldCheckBox(field);
            //fCheck.Checked = isChecked;

            //step1.
            TableCell cell1 = FieldCheckBoxGroup.CreateFieldCell();
            cell1.HorizontalAlign = HorizontalAlign.Center;
            cell1.VerticalAlign = VerticalAlign.Top;
            CheckBox _chkField = new CheckBox();
            _chkField.ID = CheckboxIDPrefix + field.InternalName;
            _chkField.Text = string.Empty;
            _chkField.Checked = isChecked;
            cell1.Controls.Add(_chkField);
            row1.Controls.Add(cell1);

            //step2.
            row1.Controls.Add(FieldCheckBoxGroup.CreateSeperatorCell());
            //step3.
            TableCell cell2 = FieldCheckBoxGroup.CreateFieldCell();
            Label _lblField = new Label();
            _lblField.Text = field.Title + field.AuthoringInfo;       
            _lblField.Attributes.Add("FOR", cell1.ID);
            cell2.Controls.Add(_lblField);
            row1.Controls.Add(cell2);
            //step4.
            TableCell cell3 = new TableCell();
            cell3.VerticalAlign = VerticalAlign.Middle;
            cell3.Attributes.Add("noWrap", "true");

            DropDownList _dropLocation = new DropDownList();
            this.SetFieldLocation(_dropLocation, this.MaxLength);
            _dropLocation.ID = "FieldOrder_" + (this._index);
            _dropLocation.ToolTip = string.Format("Position from Left: {0}", field.Title);
            //_dropLocation.Attributes.Add("name", );
            _dropLocation.Attributes.Add("onchange", string.Format("Reorder(this, {0}, {1})", this._index, this.MaxLength));
            _dropLocation.SelectedIndex = this._index;
            cell3.Controls.Add(_dropLocation);
            row1.Controls.Add(cell3);
            //step5.
            row1.Controls.Add(FieldCheckBoxGroup.CreateSeperatorCell());
            
            this.Rows.Add(row1);
        }

        public void AddCheckField(SPField field)
        {
            AddCheckField(field, false);
        }

        private void SetFieldLocation(DropDownList dp, int length)
        {
            dp.Items.Clear();
            for (int i = 0; i < length; i++)
            {
                dp.Items.Add(Convert.ToString(i + 1));
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            string script = @" <script language=JavaScript>
                function Reorder(eSelect, iCurrentField, numSelects)
            {
                var eForm = eSelect.form;
                var iNewOrder = eSelect.selectedIndex + 1;
                var iPrevOrder;
                var positions = new Array(numSelects);
                var ix;
                for (ix = 0; ix < numSelects; ix++)
                {
                    positions[ix] = 0;
                }
                for (ix = 0; ix < numSelects; ix++)
                {
                    positions[eSelect.form['{ViewOrder}' + ix].selectedIndex] = 1;
                }
                for (ix = 0; ix < numSelects; ix++)
                {
                    if (positions[ix] == 0)
                    {
                        iPrevOrder = ix + 1;
                        break;
                    }
                }
                if (iNewOrder != iPrevOrder)
                {
                    var iInc = iNewOrder > iPrevOrder? -1:1
                    var iMin = Math.min(iNewOrder, iPrevOrder);
                    var iMax = Math.max(iNewOrder, iPrevOrder);
                    for (var iField = 0; iField < numSelects; iField++)
                    {
                        if (iField != iCurrentField)
                        {
                            if (eSelect.form['{ViewOrder}' + iField].selectedIndex + 1 >= iMin &&
                                eSelect.form['{ViewOrder}' + iField].selectedIndex + 1<= iMax)
                            {
                                eSelect.form['{ViewOrder}' + iField].selectedIndex += iInc;
                            }
                        }
                    }
                }
            }
            </script>";
            writer.Write(
                script.Replace("{ViewOrder}",
                this.NamingContainer.UniqueID + "$FieldOrder_"));//.Replace("$", "_")
            base.Render(writer);
        }

        public void SetSelectedFields(string selectedFields)
        {
            foreach (TableRow row in this.Rows)
            {
                Control ctl = row.Cells[0].Controls[0];
                //Control ctl = row;
                if (ctl is CheckBox)
                {
                    CheckBox chkTemp = ctl as CheckBox;
                    var name = chkTemp.ID.Split(new string[]{CheckboxIDPrefix},StringSplitOptions.None)[1]; //get field internal name
                    //Label lbl1 = (row.Cells[2].Controls[0]) as Label;
                    if (!string.IsNullOrEmpty(selectedFields))
                    {
                        if (selectedFields.Contains(name))
                        {
                            chkTemp.Checked = true;
                        }
                    }
                    else
                    {
                        chkTemp.Checked = false;
                    }
                }
            }
        }

        public string GetSelectedFields()
        {
            string strFields = string.Empty;
            List<SelectedField> fs = new List<SelectedField>();

            foreach (TableRow row in this.Rows)
            {
                Control ctl = row.Cells[0].Controls[0];
                //Control ctl = row;
                if (ctl is CheckBox)
                {
                    CheckBox chkTemp = ctl as CheckBox;
                    if (chkTemp.Checked == true)
                    {
                        var fieldName = chkTemp.ID.Split(new string[] { CheckboxIDPrefix }, StringSplitOptions.None)[1]; //get field internal name

                        //Control ctl1 = row.Cells[2].Controls[0];
                        //string fieldName = (ctl1 as Label).Text;

                        Control ctl2 = row.Cells[3].Controls[0];
                        int index = (ctl2 as DropDownList).SelectedIndex;

                        fs.Add(new SelectedField
                        {
                            FieldName = fieldName,
                            Index = index
                        });
                    }
                }
            }          

            //排序改成非Linq语法，保持.Net2.0的编译通过, by donson 2010-6-21
            fs.Sort(new OrderByComparer());
            foreach (SelectedField f in fs)
            {
                if (string.IsNullOrEmpty(strFields))
                {
                    strFields = f.FieldName;
                }
                else
                {
                    strFields += new string(ListQueryWebPart.s_CommaSeparator) + f.FieldName;
                }
            }

            return strFields;
        }
    }
}
